//
//  Cart.m
//  mock-store
//
//  Created by aewatson on 10/20/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Cart.h"
#import "LineItem.h"

@implementation Cart

-(id)init {
    self = [super init];
    if(self) {
        lineItemArray = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

-(void)addItem: (Item*) newItem andQuantity: (int) newQuantity {
    LineItem *lineItem = [[LineItem alloc] initWithItem:newItem andQuantity:newQuantity];
    [lineItemArray addObject:lineItem];
}

-(void)removeItemAtIndex: (int) index {
    [lineItemArray removeObjectAtIndex:index];
}

-(int)getLineItemCount {
    return [lineItemArray count];
}

-(LineItem*)getLineItemAtIndex: (int) index {
    return [lineItemArray objectAtIndex:index];
}

-(void)getLineItemIndexArray {
    NSLog(@"array: %@", lineItemArray);
}

-(void)updateItemWithSKU: (NSString*) editSKU andQuantity: (NSNumber*) newQuantity {
    // find item in line item array
    for (LineItem *li in lineItemArray) {
        if([li getItemSKU] == editSKU) {
            // update quantity
            if([newQuantity intValue] > 0) {
                [li setQuantity:[newQuantity intValue]];
            } else {
                // or remove item if quantity < 1
                [lineItemArray removeObject:li];
            }
        }
    }
}

-(LineItem*)getLineItemWithSKU: (NSString*) findSKU {
    for (LineItem *li in lineItemArray) {
        if([li getItemSKU] == findSKU) {
            return li;
        }
    }
    return nil;
}

-(NSString*)getSummaryString {
    NSString *summary = [[[NSString alloc] init] autorelease];
    for (LineItem *li in lineItemArray) {
        summary = [summary stringByAppendingString:([li getLineItemSummaryString])];
        summary = [summary stringByAppendingString:@"\n"];
    }
    return summary;
}

-(NSString*)getTotalString {
    NSString *totalString;
    float total = 0;

    for (LineItem *li in lineItemArray) {
        total = total + [li getLineItemTotalFloat];
    }
    
    totalString = [NSString stringWithFormat:@"Total: $%0.2f", total];
    return totalString;
}

@end
